import { Button, Form, Input, Modal, message, Upload } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import React, { useState } from 'react';
import './UploadForm.css'
import UploadSelect from './UploadSelect';
// import FileUpload from './FileUpload'
import axios from 'axios'

var store = window.localStorage

var upload_file

const props = {
  name: 'file',
  action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
  headers: {
    authorization: 'authorization-text',
  },
  accept: '.zip,.rar,.7z',
  onChange(info) {
    var store = window.localStorage
    store.setItem("UploadFlag", "false")
    if (info.file.status !== 'uploading') {
      // console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      store.setItem("UploadFlag", "true")
      message.success(`${info.file.name} 上传成功`);
      upload_file = info.fileList[0].originFileObj
      // 测试，直接提交请求
      // axios.post('http://localhost:5000/api/uploadArticle',
      //         {
      //           "course": "NONE",
      //           "uploader": "",
      //           "type": "file",
      //           "file": info.fileList[0].originFileObj,
      //           "title": "test"
      //         }, {headers: {'Content-Type': 'multipart/form-data'}}).then(
      //           res => {
      //             alert('上传成功')
      //           }
      //         );
    } else if (info.file.status === 'error') {
      store.setItem("UploadFlag", "false")
      message.error(`${info.file.name} 上传失败`);
    }
  },
  progress: {
    strokeColor: {
      '0%': '#108ee9',
      '100%': '#87d068',
    },
    strokeWidth: 3,
    format: (percent) => percent && `${parseFloat(percent.toFixed(2))}%`,
  },
};
const FileUpload = () => (
  <Upload {...props} maxCount={1}>
    <Button icon={<UploadOutlined />}>点击上传压缩文件</Button>
  </Upload>
);

const CollectionCreateForm = ({ open, onCreate, onCancel }) => {
  const [form] = Form.useForm();
  return (
    <Modal
      open={open}
      title="上传资料"
      okText="确定"
      cancelText="取消"
      onCancel={onCancel}
      // 真正的上传在这里
      onOk={() => {
        form
          .validateFields()
          .then((values) => {
            form.resetFields();
            onCreate(values);
            var user_name = store.getItem("UserName")
            var select_type = store.getItem("UploadType")
            var upload_flag = store.getItem("UploadFlag")            
            if (select_type === "NONE") {
              alert("未选择类别，不可提交")
            }
            else if (upload_flag !== "true") {
              alert("未上传文件，不可提交")
            }
            else {
              axios.post('/api/uploadArticle',
              {
                "course": select_type,
                "uploader": user_name,
                "type": "file",
                "file": upload_file,
                "title": values.name
              }, {headers: {'Content-Type': 'multipart/form-data'}}).then(
                res => {
                  alert('上传成功')
                }
              );
              store.setItem("UploadType", "NONE")
            }
          })
          .catch((info) => {
            console.log('Validate Failed:', info);
          });
      }}
    >
      <Form
        form={form}
        layout="vertical"
        name="form_in_modal"
        initialValues={{
          modifier: 'public',
        }}
      >
        <Form.Item
          name="name"
          label="资料名称"
          rules={[
            {
              required: true,
              message: '资料名称不能为空!',
            },
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item 
          name="type" 
          label="资料类别"
        >
          <UploadSelect />
        </Form.Item>
        <Form.Item
          name="upload"
          label="资料上传"
        >
          <FileUpload />
        </Form.Item>
      </Form>
    </Modal>
  );
};
const UploadForm1 = () => {
  const [open, setOpen] = useState(false);
  const onCreate = (values) => {
    console.log('Received values of form: ', values);
    setOpen(false);
  };
  return (
    <div>
      <Button
      type='primary'
        onClick={() => {
          setOpen(true);
        }}
      >
        分享可下载资料
      </Button>
      <CollectionCreateForm
        open={open}
        onCreate={onCreate}
        onCancel={() => {
          setOpen(false);
        }}
      />
    </div>
  );
};
export default UploadForm1;